console.log("正在创建服务器")

const ws = require("nodejs-websocket");

const server = ws.createServer(function (conn) {
    serverCallbackFunction(conn)
}).listen(8081);


function serverCallbackFunction(conn) {
    console.log("新的连接")
    console.log("Sever connections = ", server.connections.length)
    //when a new message has been received.
    conn.on("text", function (str) {
        console.log("收到信息：", str)

        const message = {
            id: 1,
            title: 'Hello Client'
        };
        conn.send(JSON.stringify(message))

    })

    //when a connection has been closed.
    conn.on("close", function (code, reason) {
        onClose(conn, code, reason)
    })

    //when a connection meet error.
    conn.on("error", function (code, reason) {
        onClose(conn, code, reason);
        onError(code, reason)
    })
}


function onClose(conn, code, reason) {
    console.log("连接关闭", code, reason)
}

function onError(code, reason) {
    console.log("a connection on error:", code, reason)
}

console.log("创建服务器完毕")
